package logic

import (
	"context"
	"ewaimai/waimairpc/cache"
	"ewaimai/waimairpc/internal/svc"
	"ewaimai/waimairpc/models"
	"ewaimai/waimairpc/waimairpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LonginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLonginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LonginLogic {
	return &LonginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LonginLogic) Longin(in *waimairpc.LonginRequest) (*waimairpc.LonginResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var u models.User
	if in.Mobile != "" && in.Password != "" {
		logx.Error("请选择一种登录方式")
	}
	if in.Mobile != "" {
		if u.ID < 0 {
			logx.Errorf("用户不存在,请前去注册")
		}
		u.Mobile = in.Mobile
		if err = u.GetUserByMobile(); err != nil {
			logx.Errorf("请用手机号去登陆")
		}
		get := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile)
		if get.Val() != in.SendCode {
			logx.Errorf("短信验证码获取失败")
		}
	}
	if in.Account != "" {
		if u.ID < 0 {
			logx.Errorf("用户不存在,请前去注册")
		}
		u.Account = in.Account
		u.Password = in.Password
		if err = u.GetUserByAccount(); err != nil {
			logx.Errorf("请使用账号密码登录")
		}
		if u.Password != in.Password {
			logx.Errorf("密码错误")
		}
	}
	return &waimairpc.LonginResponse{
		Id: int64(u.ID),
	}, nil
}
